package com.mingyue.usercenter.controller;


import ch.qos.logback.core.util.StringUtil;
import com.mingyue.usercenter.common.Result;
import com.mingyue.usercenter.model.User;
import com.mingyue.usercenter.model.request.UserLoginRequest;
import com.mingyue.usercenter.model.request.UserRegisterRequest;
import com.mingyue.usercenter.service.UserService;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

import static com.mingyue.usercenter.constant.userConstant.ADMIN_ROLE;
import static com.mingyue.usercenter.constant.userConstant.USER_LOGIN_STATE;

@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {

    @Autowired
    private UserService userService;


    @PostMapping("/register")
    public Result userRegister(@RequestBody UserRegisterRequest userRegisterRequest){

        if(userRegisterRequest == null){
            return Result.error("请输入必要参数");
        }

        String userAccount = userRegisterRequest.getUserAccount();
        String userPassword = userRegisterRequest.getUserPassword();
        String userCheckPassword  = userRegisterRequest.getCheckPassword();

        if(StringUtil.isNullOrEmpty(userAccount) && StringUtil.isNullOrEmpty(userPassword)&&
                StringUtil.isNullOrEmpty(userCheckPassword)){
            return Result.error("请输入必要参数");
        }

        log.info("注册成功");
        return  userService.userRegister(userAccount,userPassword,userCheckPassword);

    }

    @PostMapping("/login")
    public Result userLogin(@RequestBody UserLoginRequest userLoginRequest, HttpServletRequest request,
    HttpSession session){
        String sessionId = session.getId();
        log.info("获取请求的sessionID{}",sessionId);

        if(userLoginRequest == null){
            return Result.error("请输入账号和密码");
        }

        String userAccount = userLoginRequest.getUserAccount();
        String userPassword = userLoginRequest.getUserPassword();


        if(StringUtil.isNullOrEmpty(userAccount) && StringUtil.isNullOrEmpty(userPassword)){
            return Result.error("账号或密码为空");
        }

        return  userService.userLogin(userAccount,userPassword,request);

    }

    /**
     * 、只有管理员能看
     * @param username
     * @param request
     * @return
     */
    @GetMapping("/search")
    public Result searchUsers(String username,HttpServletRequest request,HttpSession session){

        String sessionId = session.getId();
        log.info("查看是否一致列表的sessionID{}",sessionId);
        if(isAdmin(request) == false){
            return Result.error("无此权限");
        }

//        List<User> user  = userService.searchUser(username);
//        List<User> newUsers = new ArrayList<>();
//        for (User user1 : user) {
//            newUsers.add(userService.userTuoMin(user1));
//        }
        List<User> userList  = userService.searchUser(username);
        //这里用了steam流进行数据的过滤
        List<User> userList1 = userList.stream().map(
                s -> userService.userTuoMin(s)
        ).collect(Collectors.toList());

        return Result.success(userList1);


    }

    @DeleteMapping("/delete")
    public Result deleteUser(Integer id,HttpServletRequest request){

        if(isAdmin(request) == false){
            return Result.error("没有删除权限");
        }

        if(id <=0){
            return Result.error("id不合法");
        }

        //注意：这里是逻辑删除
        userService.removeById(id);
        return Result.success();
    }


    /**
     * 登录之后会把个人信息存储到session中，这里要是session中有值说明是登录状态
     * @param request
     * @return
     */
    @GetMapping("/userInfoById")
    public Result userInfo(HttpServletRequest request, HttpSession session){

        String sessionId = session.getId();
        log.info("查看是否一致的sessionID{}",sessionId);
        //1.首先查看是否为登录状态
        Object userObject = request.getSession().getAttribute(USER_LOGIN_STATE);
        User userInfo = (User)userObject;

        log.info("登录后的个人信息{}",userInfo);
        if(userInfo == null){
            return Result.error("未登录,无法查询个人信息");
        }

        //2.是登录态查表
        long userInfoA = userInfo.getId();
        User user = userService.getById(userInfoA);
        /**
         * 重新查表
         *  返回脱敏信息
         */

        User userInfoNew  = userService.userTuoMin(user);
        return Result.success(userInfoNew);


    }

    @PostMapping("/logout")
    public Result userLogout(HttpServletRequest request){
        userService.userLogout(request);
        return Result.success();
    }

    public boolean isAdmin(HttpServletRequest request){
        Object userObj = request.getSession().getAttribute(USER_LOGIN_STATE);
        User user = (User)userObj;

        //user判断是否是登录状态
        return user!=null && user.getRole() == ADMIN_ROLE;
    }



}
